<?php

$uid = $_G['uid'];
$user = getuserbyuid($uid);
if(empty($user)) {
    showmessage('用户信息获取失败', '', array(), array('showdialog' => true, 'locationtime' => 3));
    exit;
}

$table_er_kami_apibuy_config = C::t('#erling_kami_apibuy#er_kami_apibuy_config');
$table_er_kami_apibuy = C::t('#erling_kami_apibuy#er_kami_apibuy');
$table_er_kami_apibuy_typegroup = C::t('#erling_kami_apibuy#er_kami_apibuy_typegroup');
$table_er_kami_apibuy_typegroup_list = ($table_er_kami_apibuy_typegroup->fetch_all())['data'];
// 当get参数里没可以typegroup_id时，默认取第一个
$typegroup_id = $_GET['typegroup_id']?? $table_er_kami_apibuy_typegroup_list[0]['id'];
$page = max(1, intval($_GET['page']));
$pagesize = 20;
$table_er_kami_apibuy_type = C::t('#erling_kami_apibuy#er_kami_apibuy_type');
$table_er_kami_apibuy_type_list = ($table_er_kami_apibuy_type->fetch_all(
    $page, $pagesize, [
        'group_id' => $typegroup_id,
        'status' => 1,
    ]
));
$multipage = multi($table_er_kami_apibuy_type_list['total'], $pagesize, $page, $_G['siteurl'].'plugin.php?id=erling_kami_apibuy:user_kami_exchange&typegroup_id='.$typegroup_id);

$er_kami_apibuy_config = $table_er_kami_apibuy_config->fetch_by_keys([
    'allowed_groups','precautions', 'nav_name', 'recharge_url'
]);
$er_kami_apibuy_config['recharge_url']['value']??= 'home.php?mod=spacecp&ac=credit&op=buy';
$allowed_groups = dunserialize($er_kami_apibuy_config['allowed_groups']['value']);
// 获取用户所有用户组(主用户组+扩展用户组)
$user_groups = array($user['groupid']);
if(!empty($user['extgroupids'])) {
    $extgroups = explode("\t", trim($user['extgroupids'], "\t"));
    $user_groups = array_merge($user_groups, $extgroups);
}
$has_permission = false;
foreach($user_groups as $group) {
    if(in_array($group, $allowed_groups)) {
        $has_permission = true;
        break;
    }
}

if(!$has_permission) {
    showmessage('您的用户组无法访问', '', array(), array('showdialog' => true, 'locationtime' => 3));
    exit;
}

// 积分类型
$extcredits_array = DB::fetch_all("SELECT * FROM %t WHERE skey LIKE %s", array('common_setting', 'extcredits%'));
if ($extcredits_array && isset($extcredits_array[0]['svalue'])) {
    $extcredits_data = unserialize($extcredits_array[0]['svalue']);
} else {
    $extcredits_data = [];
}


if($_GET['apibuy_kami']) {
    if(!submitcheck('formhash')) {
        $data = [
            'success' => false,
            'message' => '请求来源验证失败'
        ];
        echo json_encode($data);
        exit;
    }
    $kamiTypeId = $_POST['kami_type'];
    $kami_apibuy_type = $table_er_kami_apibuy_type->fetch($kamiTypeId);
    
    // 验证用户积分余额是否足够扣除
    $userCredit = getuserprofile('extcredits'.$kami_apibuy_type['extcredits'], $uid);
    if($userCredit < $kami_apibuy_type['credit']) {
        $data = [
            'success' => false,
            'message' => '您的'.$extcredits_data[$kami_apibuy_type['extcredits']]['title'].'不足，需要'.$kami_apibuy_type['credit']
        ];
        echo json_encode($data);
        exit;
    }
    // 获取卡密
    // 判断kami_apibuy_type的is_api是否为1，如果是1，则调用api接口
    if($kami_apibuy_type['is_api'] == 1) {
        $table_er_kami_apibuy_configapi = C::t('#erling_kami_apibuy#er_kami_apibuy_configapi');
        $configapi = $table_er_kami_apibuy_configapi->fetch($kami_apibuy_type['configapi_id']);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $configapi['url'].'/api/kami-get');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, [
            'id' => $kami_apibuy_type['api_type_id']
        ]);
        $origin = $_SERVER['HTTP_ORIGIN']?? '';
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Origin: '. $origin,
            'Accept: application/json',
        ]);
        $response = curl_exec($ch);
        // 打印日志到当前目录下的kami_get_api.log文件中
        // if(curl_errno($ch)) {
        //     file_put_contents('kami_get_api.log', date('Y-m-d H:i:s').' - CURL Error: '.curl_error($ch)."\n", FILE_APPEND);
        // }
        curl_close($ch);
        $data = json_decode($response, true);
        // 打印日志到当前目录下的kami_get_api.log文件中
        // file_put_contents('kami_get_api.log', date('Y-m-d H:i:s').' - Response: '.json_encode($data)."\n", FILE_APPEND);
        if($data['code'] == 200) {
            $encryptedData  = $data['data'];
            // 解密
            $privateKey = $configapi['private_key'];
            // openssl_private_decrypt(base64_decode($encryptedData), $decrypted, $privateKey);
            // $kami_data = json_decode($decrypted, true);
            $chunkSize = 344; // 根据加密块大小调整
            $decrypted_data = '';

            for ($i = 0; $i < strlen($encryptedData); $i += $chunkSize) {
                $chunk = substr($encryptedData, $i, $chunkSize);
                openssl_private_decrypt(base64_decode($chunk), $decrypted, $privateKey);
                $decrypted_data .= $decrypted;
            }

            $kami_data = json_decode($decrypted_data, true);
            
            if(!empty($kami_data)){
                $apibuy_log = C::t('#erling_kami_apibuy#er_kami_apibuy_log');
                $apibuy_log->insert([
                    'uid' => $uid,
                    'title' => $kami_apibuy_type['name'],
                    'desc' => $kami_apibuy_type['desc'],
                    'kami_key' => $kami_data['key'],
                    'order_no' => $kami_data['order_no'],
                    'extcredits' => $kami_apibuy_type['extcredits'],
                    'credit' => $kami_apibuy_type['credit'],
                    'is_api' => 1, // 是否为api购买，1是、2否
                    'api_domain' => $configapi['url'],
                    'create_time' => TIMESTAMP,
                    'update_time' => TIMESTAMP,
                    'expire_time' => is_numeric($kami_data['exchange_expire_time']) ? 
                        (int)$kami_data['exchange_expire_time'] : 
                        strtotime($kami_data['exchange_expire_time']),
                ]);
                // 积分扣除
                updatemembercount($uid, $dataarr = array($kami_apibuy_type['extcredits'] => -$kami_apibuy_type['credit']), $checkgroup = true, $operation = '', $relatedid = 0, $ruletxt = '');
                $data = [
                    'success' => true,
                    'message' => '获取成功',
                    'kami' => $kami_data['key'],
                    'kami_apibuy_type' => $kami_apibuy_type['name'],
                ];
            } else {
                $data = [
                   'success' => false,
                   'message' => '获取失败'
                ];
            }
        } else {
            $data = [
              'success' => false,
              'message' => $data['msg']
            ];
        }
    } else{
        $kami = $table_er_kami_apibuy->buy_kami_by_type_id($kamiTypeId, $uid, $kami_apibuy_type['extcredits'], $kami_apibuy_type['credit']);
        if(!$kami) {
            $data = [
                'success' => false,
                'message' => '获取失败或无剩余卡密'
            ];
        } else {
            $data = [
                'success' => true,
                'message' => '获取成功',
                'kami' => $kami['kami_key'],
                'kami_apibuy_type' => $kami_apibuy_type['name'],
            ];
            $apibuy_log = C::t('#erling_kami_apibuy#er_kami_apibuy_log');
            $apibuy_log->insert([
                'uid' => $uid,
                'title' => $kami_apibuy_type['name'],
                'desc' => $kami['desc'],
                'kami_key' => $kami['kami_key'],
                'order_no' => '',
                'extcredits' => $kami_apibuy_type['extcredits'],
                'credit' => $kami_apibuy_type['credit'],
                'create_time' => TIMESTAMP,
                'update_time' => TIMESTAMP,
                'expire_time' => $kami['expire_time'],
            ]);
            // 积分扣除
            updatemembercount($uid, $dataarr = array($kami_apibuy_type['extcredits'] => -$kami_apibuy_type['credit']), $checkgroup = true, $operation = '', $relatedid = 0, $ruletxt = '');
        }
    }
    echo json_encode($data);
    exit;
}

// 获取当前用户所有积分
$credits = DB::fetch_first("SELECT * FROM %t WHERE uid=%d", array('common_member_count', $uid));
$credits = [
    'extcredits1' => [
        'value' => $credits['extcredits1'],
        'title' => $extcredits_data[1]['title']
    ],
    'extcredits2' => [
        'value' => $credits['extcredits2'],
        'title' => $extcredits_data[2]['title']
    ],
    'extcredits3' => [
        'value' => $credits['extcredits3'],
        'title' => $extcredits_data[3]['title']
    ],
    'extcredits4' => [
        'value' => $credits['extcredits4'],
        'title' => $extcredits_data[4]['title']
    ],
    'extcredits5' => [
        'value' => $credits['extcredits5'],
        'title' => $extcredits_data[5]['title']
    ],
    'extcredits6' => [
        'value' => $credits['extcredits6'],
        'title' => $extcredits_data[6]['title']
    ],
    'extcredits7' => [
        'value' => $credits['extcredits7'],
        'title' => $extcredits_data[7]['title']
    ],
    'extcredits8' => [
        'value' => $credits['extcredits8'],
        'title' => $extcredits_data[8]['title']
    ]
];

include template('erling_kami_apibuy:user_kami_exchange');